package com.example.aussiehealthhelper;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class DrugDetailActivity extends AppCompatActivity {

    private HealthDbHelper dbHelper;
    private int drugId;
    private boolean isFavorite = false;
    private TextView tvDrugName;
    private TextView tvIndication;
    private TextView tvAdverse;
    private TextView tvSimilar;
    private TextView tvDosage;
    private TextView tvNote;
    private Button btnEditNote;
    private Button btnAddFavorite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drug_detail);
        dbHelper = new HealthDbHelper(this);
        drugId = getIntent().getIntExtra("DRUG_ID", -1);
        initViews();
        if (drugId != -1) {
            new LoadDrugDetailTask().execute(drugId);
        }
        btnEditNote.setOnClickListener(v -> showEditNoteDialog());
        btnAddFavorite.setOnClickListener(v -> toggleFavoriteStatus());
    }

    private void initViews() {
        tvDrugName = findViewById(R.id.tvDrugName);
        initDetailItem(R.id.indicationItem, "适应症");
        initDetailItem(R.id.adverseItem, "不良反应");
        initDetailItem(R.id.similarItem, "相似药品");
        initDetailItem(R.id.dosageItem, "用法用量");
        initDetailItem(R.id.noteItem, "我的备注");

        //绑定值视图
        tvIndication = ((ViewGroup) findViewById(R.id.indicationItem)).findViewById(R.id.tvValue);
        tvAdverse = ((ViewGroup) findViewById(R.id.adverseItem)).findViewById(R.id.tvValue);
        tvSimilar = ((ViewGroup) findViewById(R.id.similarItem)).findViewById(R.id.tvValue);
        tvDosage = ((ViewGroup) findViewById(R.id.dosageItem)).findViewById(R.id.tvValue);
        tvNote = ((ViewGroup) findViewById(R.id.noteItem)).findViewById(R.id.tvValue);

        //初始化按钮
        btnEditNote = findViewById(R.id.btnEditNote);
        btnAddFavorite = findViewById(R.id.btnAddFavorite);
    }

    private void initDetailItem(int itemId, String labelText) {
        ViewGroup itemLayout = findViewById(itemId);
        TextView tvLabel = itemLayout.findViewById(R.id.tvLabel);
        tvLabel.setText(labelText);
    }

    private class LoadDrugDetailTask extends AsyncTask<Integer, Void, Drug> {

        @Override
        protected Drug doInBackground(Integer... params) {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            Drug drug = null;

            String[] projection = {
                    HealthDbHelper.COLUMN_DRUG_ID,
                    HealthDbHelper.COLUMN_NAME_CN,
                    HealthDbHelper.COLUMN_NAME_EN,
                    HealthDbHelper.COLUMN_INDICATION,
                    HealthDbHelper.COLUMN_INDICATION_CATEGORY,
                    HealthDbHelper.COLUMN_ADVERSE,
                    HealthDbHelper.COLUMN_SIMILAR,
                    HealthDbHelper.COLUMN_DOSAGE,
                    HealthDbHelper.COLUMN_NOTE,
                    HealthDbHelper.COLUMN_IS_FAVORITE
            };

            try (Cursor cursor = db.query(
                    HealthDbHelper.TABLE_DRUGS,
                    projection,
                    HealthDbHelper.COLUMN_DRUG_ID + " = ?",
                    new String[]{String.valueOf(params[0])},
                    null,
                    null,
                    null
            )) {
                if (cursor.moveToFirst()) {
                    drug = new Drug(
                            cursor.getInt(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_DRUG_ID)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_NAME_CN)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_NAME_EN)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_INDICATION)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_INDICATION_CATEGORY)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_ADVERSE)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_SIMILAR)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_DOSAGE)),
                            cursor.getString(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_NOTE)),
                            cursor.getInt(cursor.getColumnIndexOrThrow(HealthDbHelper.COLUMN_IS_FAVORITE)) == 1
                    );
                }
            } catch (Exception e) {
                Log.e("DrugDetail", "数据库查询错误: " + e.getMessage());
            }
            return drug;
        }

        @Override
        protected void onPostExecute(Drug drug) {
            if (drug != null) {
                tvDrugName.setText(drug.getNameCN() + " / " + drug.getNameEN());
                setSafeText(tvIndication, drug.getIndication());
                setSafeText(tvAdverse, drug.getAdverseReaction());
                setSafeText(tvSimilar, drug.getSimilarDrugs());
                setSafeText(tvDosage, drug.getDosage());
                setSafeText(tvNote, drug.getNote());
                isFavorite = drug.getIsFavorite();
                updateFavoriteButton();
            } else {
                Log.e("DrugDetail", "没有找到药品信息");
            }
        }

        private void setSafeText(TextView textView, String content) {
            if (content != null && !content.trim().isEmpty()) {
                textView.setText(content);
            } else {
                textView.setText("-- 暂无相关信息 --");
                textView.setTextColor(getResources().getColor(android.R.color.darker_gray));
            }
        }
    }

    //更新收藏按钮状态
    private void updateFavoriteButton() {
        if (isFavorite) {
            btnAddFavorite.setText("已收藏");
            btnAddFavorite.setBackgroundResource(R.drawable.button_background_fav_selected);
        } else {
            btnAddFavorite.setText("加入收藏");
            btnAddFavorite.setBackgroundResource(R.drawable.button_background_fav);
        }
    }

    //切换收藏状态
    private void toggleFavoriteStatus() {
        isFavorite = !isFavorite;

        new Thread(() -> {
            int result = dbHelper.toggleFavoriteStatus(drugId, isFavorite);

            runOnUiThread(() -> {
                if (result > 0) {
                    Toast.makeText(DrugDetailActivity.this,
                            isFavorite ? "已加入收藏" : "已取消收藏",
                            Toast.LENGTH_SHORT).show();
                    updateFavoriteButton();
                } else {
                    Toast.makeText(DrugDetailActivity.this,
                            "操作失败，请重试",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }).start();
    }

    //显示编辑备注对话框
    private void showEditNoteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("编辑备注");

        //设置输入框
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        input.setText(tvNote.getText().toString().replace("-- 暂无相关信息 --", ""));
        input.setMinHeight(200);
        builder.setView(input);

        //设置按钮
        builder.setPositiveButton("保存", (dialog, which) -> {
            String newNote = input.getText().toString();
            updateDrugNote(newNote);
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }


    private void updateDrugNote(String newNote) {

        setSafeText(tvNote, newNote);

        new Thread(() -> {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(HealthDbHelper.COLUMN_NOTE, newNote);

            try {
                int result = db.update(
                        HealthDbHelper.TABLE_DRUGS,
                        values,
                        HealthDbHelper.COLUMN_DRUG_ID + " = ?",
                        new String[]{String.valueOf(drugId)}
                );

                runOnUiThread(() -> {
                    if (result > 0) {
                        Toast.makeText(DrugDetailActivity.this,
                                "备注已更新", Toast.LENGTH_SHORT).show();

                        // 刷新药品对象（确保数据一致性）
                        new LoadDrugDetailTask().execute(drugId);
                    } else {
                        Toast.makeText(DrugDetailActivity.this,
                                "更新失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() -> {
                    Toast.makeText(DrugDetailActivity.this,
                            "数据库错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    // 恢复原有
                    Drug currentDrug = dbHelper.getDrugById(drugId);
                    if (currentDrug != null) {
                        setSafeText(tvNote, currentDrug.getNote());
                    }
                });
            } finally {
                db.close();
            }
        }).start();
    }


    private void setSafeText(TextView textView, String content) {
        if (content != null && !content.trim().isEmpty()) {
            textView.setText(content);
            textView.setTextColor(getResources().getColor(android.R.color.black));
        } else {
            textView.setText("-- 暂无相关信息 --");
            textView.setTextColor(getResources().getColor(android.R.color.darker_gray));
        }
    }

    @Override
    protected void onDestroy() {
        if (dbHelper != null) {
            dbHelper.close();
        }
        super.onDestroy();
    }
}